package com.somiz.reparation;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.LineBorder;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;

import org.freixas.jcalendar.JCalendarCombo;
import org.hibernate.Session;

import com.gest.util.Dates;
import com.gest.util.FilterComboBox;
import com.gest.util.PdfUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.somiz.admin.Admin;
import com.somiz.article.Article;
import com.somiz.main.Control;
import com.somiz.main.Principal;
import com.somiz.structure.Structure;
import com.tech.hibernate.HibernateUtil;

/**
 * 
 * @author kacem
 * @version 1.0
 * 
 */
public class ReparationPanListe extends JPanel {
	private static final long serialVersionUID = 2672634149992839657L;
	private ModelListeReparation modelListeReparation = new ModelListeReparation();
	private JTable tableau;
	private JCalendarCombo C_dateDe;
	private JCalendarCombo C_dateJusq;
	private FilterComboBox C_reparateur;
	private FilterComboBox C_strct;
	private JComboBox C_extInt;
	private int sorteCol = 0;
	private int sence = 0;

	public ReparationPanListe() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		C_strct = ListeCombStructure(session, C_strct);
		C_strct.getTextfield().addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		C_strct.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		C_reparateur = ListeCombReparateur(session, C_reparateur);
		C_reparateur.getTextfield().addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		C_reparateur.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		session.close();
		setLayout(null);
		tableau = new JTable(modelListeReparation);
		tableau.setRowHeight(25);
		JScrollPane scrollPane = new JScrollPane(tableau);
		scrollPane.setBounds(0, 72, 913, 446);
		this.add(scrollPane);

		JPanel panel = new JPanel();
		panel.setLayout(null);
		panel.setBorder(new LineBorder(new Color(0, 0, 0)));
		panel.setBounds(181, 11, 681, 50);
		add(panel);

		JLabel lblCode = new JLabel("De:");
		lblCode.setBounds(0, 4, 37, 34);
		panel.add(lblCode);

		C_dateDe = new JCalendarCombo(JCalendarCombo.DISPLAY_DATE
				| JCalendarCombo.DISPLAY_TIME, true);
		C_dateDe.setDateFormat(new SimpleDateFormat("dd-MM-yyyy"));
		C_dateDe.setEditable(true);
		C_dateDe.setBounds(24, 4, 90, 34);
		panel.add(C_dateDe);
		C_dateDe.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});

		JLabel lblFamille = new JLabel("jusqu :");
		lblFamille.setBounds(116, 4, 37, 34);
		panel.add(lblFamille);

		JLabel lblGamme = new JLabel("Reparateur :");
		lblGamme.setBounds(245, 4, 62, 34);
		panel.add(lblGamme);

		JLabel lblStructure = new JLabel("structure :");
		lblStructure.setBounds(403, 4, 51, 34);
		panel.add(lblStructure);

		JLabel lblExtint = new JLabel("ext./int.:");
		lblExtint.setBounds(544, 4, 51, 34);
		panel.add(lblExtint);

		C_dateJusq = new JCalendarCombo(JCalendarCombo.DISPLAY_DATE
				| JCalendarCombo.DISPLAY_TIME, true);
		C_dateJusq.setDateFormat(new SimpleDateFormat("dd-MM-yyyy"));
		C_dateJusq.setEditable(true);
		C_dateJusq.setBounds(152, 4, 90, 34);
		panel.add(C_dateJusq);
		C_dateJusq.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		C_reparateur.setBounds(306, 4, 96, 34);
		panel.add(C_reparateur);

		C_strct.setBounds(456, 4, 78, 34);
		panel.add(C_strct);

		C_extInt = new JComboBox();
		C_extInt.addItem("");
		C_extInt.addItem("interne");
		C_extInt.addItem("externe");
		C_extInt.setBounds(586, 4, 85, 34);
		panel.add(C_extInt);
		C_extInt.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		JButton button = new JButton("");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				Control.getReparationForm().vider(session);
				Control.getPrincipal()
						.getTabbedPane()
						.addTab("Reparations",
								new ImageIcon(
										Principal.class
												.getResource("/cc/black/png/cert_icon&16.png")),
								Control.getReparationForm(), null);
				Control.getPrincipal()
						.getTabbedPane()
						.setSelectedIndex(
								Control.getPrincipal().getTabbedPane()
										.getTabCount() - 1);
				session.close();
			}
		});
		button.setIcon(new ImageIcon(ReparationPanListe.class
				.getResource("/images/png/Add32.png")));
		button.setPreferredSize(new Dimension(50, 50));
		button.setMnemonic(KeyEvent.VK_ENTER);
		button.setBackground(Color.WHITE);
		button.setBounds(6, 11, 50, 50);
		add(button);

		JButton button_1 = new JButton("");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		button_1.setIcon(new ImageIcon(ReparationPanListe.class
				.getResource("/cc/black/png/reload_icon&32.png")));
		button_1.setPreferredSize(new Dimension(50, 50));
		button_1.setMnemonic(KeyEvent.VK_ENTER);
		button_1.setBackground(Color.WHITE);
		button_1.setBounds(66, 11, 50, 50);
		add(button_1);

		JButton button_2 = new JButton("");
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				creerPdfArticle(session, "c:/temp/listereparatios.pdf");
				PdfUtil.OuvrirePdf("c:/temp/listereparatios.pdf",
						"Parc informatique");
				session.close();
			}
		});
		button_2.setIcon(new ImageIcon(ReparationPanListe.class
				.getResource("/cc/black/png/doc_lines_stright_icon&32.png")));
		button_2.setPreferredSize(new Dimension(50, 50));
		button_2.setMnemonic(KeyEvent.VK_ENTER);
		button_2.setBackground(Color.WHITE);
		button_2.setBounds(128, 11, 50, 50);
		add(button_2);

		JButton button_3 = new JButton("");
		button_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				viderFiltres(session);
				session.close();
			}
		});
		button_3.setIcon(new ImageIcon(ReparationPanListe.class
				.getResource("/cc/black/png/trash_icon&32.png")));
		button_3.setPreferredSize(new Dimension(50, 50));
		button_3.setMnemonic(KeyEvent.VK_ENTER);
		button_3.setBackground(Color.WHITE);
		button_3.setBounds(863, 11, 50, 50);
		add(button_3);
		tableau.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				int selectedRow = tableau.rowAtPoint(arg0.getPoint());
				int selectedCol = tableau.columnAtPoint(arg0.getPoint());
				if (selectedRow != -1)
					tableau.changeSelection(selectedRow, -1, false, false);
				if (selectedCol != -1)
					tableau.changeSelection(-1, selectedCol, false, false);
				if (arg0.getClickCount() == 2) {
					JTable target = (JTable) arg0.getSource();
					int row = target.getSelectedRow();
					int column = target.getSelectedColumn();
					Session session = HibernateUtil.getSessionFactory()
							.openSession();
					Reparation reparation = new Reparation();
					reparation.setDateRecep(Dates.stringToDate(tableau
							.getValueAt(row, 1).toString()));
					Article article = new Article();
					article.setCode(tableau.getValueAt(row, 2).toString());
					reparation.setArticle(Control.getArticleDao()
							.TrouverAvecCode(article, session));
					reparation = Control.getReparationDao()
							.TrouverAvecDateEtArticle(reparation, session);
					Control.getReparationForm().vider(session);
					Control.getReparationForm().ReparationVersForm(reparation);
					Control.getReparationForm().setReparationId(
							reparation.getId());
					Control.getPrincipal()
							.getTabbedPane()
							.addTab("Reparation",
									new ImageIcon(
											Principal.class
													.getResource("/cc/black/png/cert_icon&16.png")),
									Control.getReparationForm(), null);
					Control.getPrincipal()
							.getTabbedPane()
							.setSelectedIndex(
									Control.getPrincipal().getTabbedPane()
											.getTabCount() - 1);
					session.close();
				}
			}
		});
		JTableHeader header = tableau.getTableHeader();
		header.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				if (arg0.getClickCount() == 1) {
					Session session = HibernateUtil.getSessionFactory()
							.openSession();
					TableColumnModel colModel = tableau.getColumnModel();
					int columnModelIndex = colModel.getColumnIndexAtX(arg0
							.getX());
					int modelIndex = colModel.getColumn(columnModelIndex)
							.getModelIndex();
					if (sence < 0)
						sence = 1;
					else
						sence = -1;
					sorteCol = modelIndex;
					actualisationFiltre(session);
					session.close();
				}
			}
		});
		session = HibernateUtil.getSessionFactory().openSession();
		actualisationFiltre(session);
		session.close();
	}

	public void creerPdfArticle(Session session, String lien) {
		String FILE = lien;
		Font catFont = new Font(Font.SERIF, 18, Font.BOLD);
		PdfPTable table = new PdfPTable(8);
		try {
			Document document = new Document();
			PdfWriter.getInstance(document, new FileOutputStream(FILE));
			document.open();
			document.addTitle("Liste des reparations");
			Paragraph preface = new Paragraph();
			PdfUtil.addEmptyLine(preface, 2);
			document.add(preface);
			List<Reparation> reparations = new ArrayList<Reparation>(0);
			reparations = Control.getReparationDao().charger(new Reparation(),
					session);
			reparations = filreStructure(reparations, C_strct);
			reparations = filreReparateur(reparations, C_reparateur);
			reparations = filreReparationsAvantDate(C_dateJusq, reparations);
			reparations = filtreReparationsApresDate(C_dateDe, reparations);
			reparations = filreExtInt(reparations, C_extInt);
			table = modelListeReparation.CreerHeaderPdf(table);
			for (int i = 0; i < reparations.size(); i++) {
				table = modelListeReparation.addObjectPDF(reparations.get(i),
						table);
			}
			document.add(table);
			document.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void viderFiltres(Session session) {
		C_strct.RemplireComboListe(Control.getStructureDao()
				.ListeCodesStructures(session));
		C_reparateur.RemplireComboListe(Control.getAdminDao().ListeNomUser(
				session));
		C_extInt.setSelectedIndex(0);
		C_dateDe.setSelectedItem("");
		C_dateJusq.setSelectedItem("");
	}

	public void actualisationFiltre(Session session) {
		modelListeReparation.removeAllObjects();
		List<Reparation> reparations = new ArrayList<Reparation>(0);
		Reparation reparation = new Reparation();
		reparations = Control.getReparationDao().charger(reparation, session);
		reparations = filreStructure(reparations, C_strct);
		reparations = filreReparateur(reparations, C_reparateur);
		reparations = filreReparationsAvantDate(C_dateJusq, reparations);
		reparations = filtreReparationsApresDate(C_dateDe, reparations);
		reparations = filreExtInt(reparations, C_extInt);
		if (sence != 0)
			reparations = trier(sorteCol, sence, reparations);

		for (int i = 0; i < reparations.size(); i++) {
			modelListeReparation.addObject(reparations.get(i));
		}
	}

	public FilterComboBox ListeCombStructure(Session session,
			FilterComboBox comboBox) {
		Structure structure = new Structure();
		List<Structure> structures = Control.getStructureDao().charger(
				structure, session);
		List<String> listeRet = new ArrayList<String>();
		listeRet.add("");
		if (structure != null) {
			for (int i = 0; i < structures.size(); i++) {
				listeRet.add(structures.get(i).getCode());
			}
		}
		comboBox = new FilterComboBox(listeRet);
		return comboBox;
	}

	public FilterComboBox ListeCombReparateur(Session session,
			FilterComboBox comboBox) {
		Admin admin = new Admin();
		List<Admin> admins = Control.getAdminDao().charger(admin, session);
		List<String> listeRet = new ArrayList<String>();
		listeRet.add("");
		if (admin != null) {
			for (int i = 0; i < admins.size(); i++) {
				listeRet.add(admins.get(i).getNom());
			}
		}
		comboBox = new FilterComboBox(listeRet);
		return comboBox;
	}

	public List<Reparation> filreExtInt(List<Reparation> reparations,
			JComboBox combo) {
		String sFiltre = combo.getSelectedItem().toString();
		List<Reparation> reparationsRet = new ArrayList<Reparation>();
		if (!combo.getSelectedItem().toString().equals("")) {
			if (combo.getSelectedItem().toString().equals("externe")) {
				for (int i = 0; i < reparations.size(); i++) {
					if (reparations.get(i).getRepExt() != null) {
						reparationsRet.add(reparations.get(i));
					}
				}
			} else {
				for (int i = 0; i < reparations.size(); i++) {
					if (reparations.get(i).getRepExt() == null) {
						reparationsRet.add(reparations.get(i));
					}
				}
			}
			return reparationsRet;
		} else {
			return reparations;
		}
	}

	public List<Reparation> filreReparateur(List<Reparation> reparations,
			FilterComboBox combo) {
		String sFiltre = combo.getSelectedItem().toString();
		List<Reparation> reparationsRet = new ArrayList<Reparation>();
		if (!combo.getSelectedItem().toString().equals("")) {
			for (int i = 0; i < reparations.size(); i++) {
				if (reparations.get(i).getReparateur().getNom().length() >= combo
						.getSelectedItem().toString().length()
						&& sFiltre.equals(reparations
								.get(i)
								.getReparateur()
								.getNom()
								.substring(
										0,
										combo.getSelectedItem().toString()
												.length()))) {
					reparationsRet.add(reparations.get(i));
				}
			}
			return reparationsRet;
		} else {
			return reparations;
		}
	}

	public List<Reparation> filreStructure(List<Reparation> reparations,FilterComboBox combo) {
		String sFiltre = combo.getSelectedItem().toString();
		List<Reparation> reparationsRet = new ArrayList<Reparation>();
		if (!combo.getSelectedItem().toString().equals("")) {
			for (int i = 0; i < reparations.size(); i++) {
				if (reparations.get(i).getStructure() != null) {
					if (reparations.get(i).getStructure().getCode().length() >= combo.getSelectedItem().toString().length()
							&& sFiltre.equals(reparations.get(i).getStructure().getCode().substring(0,
											combo.getSelectedItem().toString().length()))) {
						reparationsRet.add(reparations.get(i));
					}
				}
			}
			return reparationsRet;
		} else {
			return reparations;
		}
	}

	public List<Reparation> filreReparationsAvantDate(
			JCalendarCombo calendarCombo, List<Reparation> reparations) {
		List<Reparation> reparationsRet = new ArrayList<Reparation>(0);
		if (!calendarCombo.getSelectedItem().toString().equals("")) {
			for (int i = 0; i < reparations.size(); i++) {
				if (reparations.get(i).getDateRecep()
						.compareTo(calendarCombo.getDate()) != 1) {
					reparationsRet.add(reparations.get(i));
				}
			}
			return reparationsRet;
		} else {
			return reparations;
		}
	}

	public List<Reparation> filtreReparationsApresDate(
			JCalendarCombo calendarCombo, List<Reparation> reparations) {
		List<Reparation> reparationsRet = new ArrayList<Reparation>(0);
		if (!calendarCombo.getSelectedItem().toString().equals("")) {
			for (int i = 0; i < reparations.size(); i++) {
				if (reparations.get(i).getDateRecep()
						.compareTo(calendarCombo.getDate()) != -1) {
					reparationsRet.add(reparations.get(i));
				}
			}
			return reparationsRet;
		} else {
			return reparations;
		}
	}

	// dateRecep
	public Comparator<Reparation> ordreDateRecep = new Comparator<Reparation>() {
		@Override
		public int compare(Reparation b1, Reparation b2) {
			return b2.getDateRecep().compareTo(b1.getDateRecep());
		}
	};
	public Comparator<Reparation> ordreInvDateRecep = new Comparator<Reparation>() {
		@Override
		public int compare(Reparation b1, Reparation b2) {
			return b1.getDateRecep().compareTo(b2.getDateRecep());
		}
	};
	// equipement
	public Comparator<Reparation> ordreEquip = new Comparator<Reparation>() {
		@Override
		public int compare(Reparation b1, Reparation b2) {
			return b2.getArticle().getCode()
					.compareTo(b1.getArticle().getCode());
		}
	};
	public Comparator<Reparation> ordreInvEquip = new Comparator<Reparation>() {
		@Override
		public int compare(Reparation b1, Reparation b2) {
			return b1.getArticle().getCode()
					.compareTo(b2.getArticle().getCode());
		}
	};

	/**
	 * 
	 * @param Col
	 *            : la colomn du champ
	 * @param sence
	 *            : 1 pour normal -1 pour invers
	 */
	public List<Reparation> trier(int Col, int sence,
			List<Reparation> reparations) {
		if (Col == 0) {
			if (sence > 0)
				Collections.sort(reparations, ordreEquip);
			else
				Collections.sort(reparations, ordreInvEquip);
		}
		if (Col == 1) {
			if (sence > 0)
				Collections.sort(reparations, ordreDateRecep);
			else
				Collections.sort(reparations, ordreInvDateRecep);
		}
		return reparations;
	}
}
